import { useEffect, useState, useRef } from 'preact/hooks';
import { isConnected, deviceInfo, currentPath } from '../app';
import firmwareVersionToString from '../global';

// 定义设备信息类型
/** @typedef {{ firmwareVersion: number }} DeviceInfo */

/**
 * @param {{ onRouteChange?: any }} [props]
 */
export default function Sidebar({ onRouteChange } = /** @type {{ onRouteChange?: any }} */({})) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const heartbeatTimer = useRef(null);
  const heartbeatTimeout = useRef(null);
  const isHeartbeatPending = useRef(false);

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };

  // 心跳检测函数
  const checkHeartbeat = async () => {
    // 如果上一次心跳还未完成，则不发送新的心跳
    if (isHeartbeatPending.current) {
      return;
    }

    isHeartbeatPending.current = true;

    try {
      const controller = new AbortController();
      heartbeatTimeout.current = setTimeout(() => {
        controller.abort();
        isConnected.value = false;
      }, 3000); // 3秒超时

      const response = await fetch("/api/heartbeat", {
        signal: controller.signal
      });

      if (response.status === 403) {
        isConnected.value = false;
      } else {
        const data = await response.json();
        isConnected.value = true;
        deviceInfo.value = data;
      }
    } catch (error) {
      if (error.name === 'AbortError') {
        console.log('心跳检测超时');
        isConnected.value = false;
      } else {
        console.error('心跳检测错误:', error);
        isConnected.value = false;
      }
    } finally {
      clearTimeout(heartbeatTimeout.current);
      isHeartbeatPending.current = false;
    }
  };

  const menuItems = [
    { 
      path: '/', 
      title: '欢迎', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
        </svg>
      )
    },
    { 
      path: '/device-status', 
      title: '设备状态', 
      icon: (
        <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
          <path d="M7.934 16.066a.75.75 0 1 1-1.06 1.06a7.25 7.25 0 0 1 6.798-12.181a.75.75 0 1 1-.344 1.46a5.75 5.75 0 0 0-5.393 9.661m9.954-6.924a.75.75 0 0 1 .955.46a7.25 7.25 0 0 1-1.716 7.525a.75.75 0 1 1-1.061-1.061a5.75 5.75 0 0 0 1.362-5.969a.75.75 0 0 1 .46-.955M15.88 6.667a.625.625 0 0 1 .962.761l-.13.25a355 355 0 0 1-1.415 2.713a155 155 0 0 1-1.156 2.157c-.171.31-.326.586-.452.803a5 5 0 0 1-.32.5a1.875 1.875 0 0 1-2.94-2.327c.086-.109.244-.265.413-.425c.182-.173.414-.387.678-.625a154 154 0 0 1 1.832-1.62a375 375 0 0 1 2.314-2.003zM22 12c0 5.523-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2s10 4.477 10 10M3.5 12a8.5 8.5 0 1 0 17 0a8.5 8.5 0 0 0-17 0"/>
        </svg>
      )
    },
    { 
      path: '/onboard-peripherals', 
      title: '板载外设', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
        </svg>
      )
    },
    { 
      path: '/ethercat-slave', 
      title: 'EtherCAT Slave', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
        </svg>
      )
    },
    { 
      path: '/settings', 
      title: '设置', 
      icon: (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      )
    }
  ];

  useEffect(() => {
    // 启动心跳检测
    checkHeartbeat(); // 立即执行一次
    heartbeatTimer.current = setInterval(checkHeartbeat, 1000); // 每秒执行一次

    // 清除定时器
    return () => {
      clearInterval(heartbeatTimer.current);
      clearTimeout(heartbeatTimeout.current);
    };
  }, []); // 空依赖数组确保定时器只在组件挂载时启动一次

  const handleClick = (path) => (e) => {
    e.preventDefault();
    if (path !== currentPath.value) {
      currentPath.value = path;
      window.history.pushState({}, '', path);
      // 触发路由更新
      window.dispatchEvent(new PopStateEvent('popstate'));
    }
  };

  return (
    <div className={`sidebar min-h-screen ${isCollapsed ? 'w-16' : 'w-64'} transition-all duration-300 ease-in-out relative`}
         style={{ background: 'var(--adonis-panel)', borderRight: '1px solid var(--adonis-border)' }}>
      <div className={`p-4 border-b transition-all duration-300 ${isCollapsed ? 'opacity-0 h-0 p-0 overflow-hidden border-none' : 'opacity-100'}`}
           style={{ borderColor: 'var(--adonis-border)' }}>
        <div className="flex flex-col">
          <div className="flex items-center space-x-2">
            <div className="w-1 h-5" style={{ background: 'var(--adonis-accent)' }}></div>
            <h1 className="font-['Orbitron'] text-xl font-bold tracking-wider"
                style={{ background: 'linear-gradient(90deg, var(--adonis-accent) 0%, var(--adonis-accent-strong) 100%)', WebkitBackgroundClip: 'text', color: 'transparent' }}>
              HPM5E-EC-DEV
            </h1>
          </div>
          <div className="mt-1 ml-3 flex items-center">
            <span className="text-[9px] tracking-[0.15em] font-medium uppercase" style={{ color: 'var(--adonis-text-muted)' }}>Device Dashboard</span>
          </div>
        </div>
        <div className="mt-2 px-2">
          <div className="flex items-center justify-between text-xs" style={{ color: 'var(--adonis-text-muted)' }}>
            <div className="flex items-center">
              <div className={`w-1.5 h-1.5 rounded-full mr-1.5 ${isConnected.value ? 'animate-pulse' : ''}`} 
                   style={{ background: isConnected.value ? 'var(--adonis-success)' : 'var(--adonis-danger)' }}></div>
              <span className="font-medium">{isConnected.value ? 'ONLINE' : 'OFFLINE'}</span>
            </div>
            <div className="flex items-center">
              <svg className="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
              </svg>
              <span>FW {
                (() => {
                  const info = /** @type {DeviceInfo} */ (/** @type {unknown} */ (deviceInfo.value));
                  return info?.firmwareVersion ? firmwareVersionToString(info.firmwareVersion) : '0.0.0';
                })()
              }</span>
            </div>
          </div>
        </div>
      </div>

      <nav className={`${isCollapsed ? 'mt-4' : 'mt-2'}`}>
        {menuItems.map((item) => (
          <a
            key={item.path}
            href={item.path}
            className={`flex items-center h-10 px-4 transition-all duration-200 relative`}
            style={{
              color: currentPath.value === item.path ? 'var(--adonis-text)' : 'var(--adonis-text-muted)',
              background: currentPath.value === item.path ? 'rgba(138,180,255,0.12)' : 'transparent',
              borderRight: currentPath.value === item.path ? '3px solid var(--adonis-accent)' : '3px solid transparent'
            }}
            onClick={handleClick(item.path)}
          >
            <div className={`flex items-center justify-center ${isCollapsed ? 'w-full' : 'w-6 mr-3'}`}>
              <div className="w-5 h-5">
                {item.icon}
              </div>
            </div>
            <span className={`text-sm transition-opacity duration-300 whitespace-nowrap ${
              isCollapsed ? 'opacity-0 w-0 overflow-hidden' : 'opacity-100'
            }`}>
              {item.title}
            </span>
          </a>
        ))}
      </nav>

      <button 
        className={`absolute bottom-4 flex items-center justify-center rounded-lg transition-all duration-300 ${
          isCollapsed 
            ? 'left-2 right-2 h-10' 
            : 'left-4 right-4 h-12'
        }`}
        style={{
          color: 'var(--adonis-text)',
          background: 'var(--adonis-panel-2)',
          border: '1px solid var(--adonis-border)'
        }}
        onClick={toggleSidebar}
        title={isCollapsed ? '展开侧边栏' : '收起侧边栏'}
      >
        <div className="flex items-center space-x-2">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d={isCollapsed ? "M4 6h16M4 12h16M4 18h16" : "M15 19l-7-7 7-7"} />
          </svg>
          {!isCollapsed && (
            <span className="text-sm font-medium transition-opacity duration-300">
              {isCollapsed ? '展开' : '收起'}
            </span>
          )}
        </div>
      </button>
    </div>
  );
}